﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using navigation.Data;
using navigation.Controls;
using System.Collections.ObjectModel;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation;

namespace navigation.Contents
{
    /// <summary>
    /// Interaction logic for ScrumBoardScreen.xaml
    /// </summary>
    public partial class ScrumBoardScreen : UserControl
    {
        public ScrumBoardScreen()
        {
            InitializeComponent();
        }

        public static DependencyProperty ScrumBoardItemsProperty = DependencyProperty.Register("ScrumBoardItems", typeof(ObservableCollection<UserStory>), typeof(ScrumBoardScreen));

        public ObservableCollection<UserStory> ScrumBoardItems
        {
            get
            {
                return (ObservableCollection<UserStory>)GetValue(ScrumBoardScreen.ScrumBoardItemsProperty);
            }
            set
            {
                SetValue(ScrumBoardScreen.ScrumBoardItemsProperty, value);
            }
        }
        
        private void PlannedButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (UserStory us in sp.Items)
            {
                SurfaceListBoxItem item = sp.ItemContainerGenerator.ContainerFromItem(us) as SurfaceListBoxItem;
                ScrumBoardTasksContainer sbtc = FindVisualChildByTag<ScrumBoardTasksContainer>(item, "PlannedBox");
                if (sbtc.TasksListBox.Visibility == System.Windows.Visibility.Visible)
                {
                    sbtc.TasksListBox.Visibility = System.Windows.Visibility.Collapsed;
                    sbtc.TasksStack.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    sbtc.TasksListBox.Visibility = System.Windows.Visibility.Visible;
                    sbtc.TasksStack.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            
        }

        private void InProgressButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (UserStory us in sp.Items)
            {
                SurfaceListBoxItem item = sp.ItemContainerGenerator.ContainerFromItem(us) as SurfaceListBoxItem;
                ScrumBoardTasksContainer sbtc = FindVisualChildByTag<ScrumBoardTasksContainer>(item, "InProgressBox");
                if (sbtc.TasksListBox.Visibility == System.Windows.Visibility.Visible)
                {
                    sbtc.TasksListBox.Visibility = System.Windows.Visibility.Collapsed;
                    sbtc.TasksStack.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    sbtc.TasksListBox.Visibility = System.Windows.Visibility.Visible;
                    sbtc.TasksStack.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        private void DoneButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (UserStory us in sp.Items)
            {
                SurfaceListBoxItem item = sp.ItemContainerGenerator.ContainerFromItem(us) as SurfaceListBoxItem;
                ScrumBoardTasksContainer sbtc = FindVisualChildByTag<ScrumBoardTasksContainer>(item, "DoneBox");
                if (sbtc.TasksListBox.Visibility == System.Windows.Visibility.Visible)
                {
                    sbtc.TasksListBox.Visibility = System.Windows.Visibility.Collapsed;
                    sbtc.TasksStack.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    sbtc.TasksListBox.Visibility = System.Windows.Visibility.Visible;
                    sbtc.TasksStack.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        public static T FindVisualChildByTag<T>(DependencyObject parent, string name) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                //string controlName = child.GetValue(Control.NameProperty) as string;

                string tag = child.GetValue(Control.TagProperty) as string;

                if (tag == name)
                {
                    return child as T;
                }
                else
                {
                    T result = FindVisualChildByTag<T>(child, name);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }        

        private void sp_HoldGesture(object sender, TouchEventArgs e)
        {
            //Console.WriteLine(e.OriginalSource);
            FrameworkElement findSource = e.OriginalSource as FrameworkElement;
            SurfaceListBoxItem draggedElement = null;

            while (draggedElement == null && findSource != null)
            {
                if ((draggedElement = findSource as SurfaceListBoxItem) == null)
                {
                    findSource = VisualTreeHelper.GetParent(findSource) as FrameworkElement;
                }
            }

            if (draggedElement == null)
            {
                return;
            }

            //foreach(UserStory us in sp.Items)
            //{
            //    SurfaceListBoxItem item = sp.ItemContainerGenerator.ContainerFromItem(us) as SurfaceListBoxItem;
            //    ScrumBoardTasksContainer sbtc1 = FindVisualChildByTag<ScrumBoardTasksContainer>(item, "PlannedBox");
            //    ScrumBoardTasksContainer sbtc2 = FindVisualChildByTag<ScrumBoardTasksContainer>(item, "InProgressBox");
            //    ScrumBoardTasksContainer sbtc3 = FindVisualChildByTag<ScrumBoardTasksContainer>(item, "DoneBox");

            //    sbtc1.IsEnabled = false;
            //    sbtc2.IsEnabled = false;
            //    sbtc3.IsEnabled = false;
            //}

            // Create the cursor visual.
            ContentControl cursorVisual = new ContentControl()
            {
                Content = draggedElement.DataContext,                
                Style = FindResource("CursorStyle") as Style

            };

            // Create a list of input devices. Add the touches that
            // are currently captured within the dragged element and
            // the current touch (if it isn't already in the list).
            List<InputDevice> devices = new List<InputDevice>();
            devices.Add(e.Device);
            foreach (InputDevice device in draggedElement.TouchesCapturedWithin)
            {
                if (device != e.Device)
                {
                    devices.Add(device);
                }
            }

            // Get the drag source object
            ItemsControl dragSource = ItemsControl.ItemsControlFromItemContainer(draggedElement);

            SurfaceDragCursor startDragOkay =
                SurfaceDragDrop.BeginDragDrop(
                  dragSource,                 // The SurfaceListBox object that the cursor is dragged out from.
                  draggedElement,             // The SurfaceListBoxItem object that is dragged from the drag source.
                  cursorVisual,               // The visual element of the cursor.
                  draggedElement.DataContext, // The data associated with the cursor.
                  devices,                    // The input devices that start dragging the cursor.
                  DragDropEffects.Move);      // The allowed drag-and-drop effects of the operation.

            // If the drag began successfully, set e.Handled to true. 
            // Otherwise SurfaceListBoxItem captures the touch 
            // and causes the drag operation to fail.
            e.Handled = (startDragOkay != null);
            draggedElement.Visibility = System.Windows.Visibility.Hidden;
        }

        private void sp_Drop(object sender, SurfaceDragDropEventArgs e)
        {
            if (e.Cursor.Data is UserStory)
            {
                int index = this.GetListBoxItemCurrentIndex(sp, e.Cursor.GetPosition);
                int indexOfDraggedElement = ScrumBoardItems.IndexOf(e.Cursor.Data as UserStory);

                if (index < 0 || index > sp.Items.Count - 1)
                {
                    UserStory temp = ScrumBoardItems[indexOfDraggedElement];
                    ScrumBoardItems.RemoveAt(indexOfDraggedElement);
                    ScrumBoardItems.Add(temp);
                }
                else
                {
                    UserStory temp = ScrumBoardItems[indexOfDraggedElement];
                    ScrumBoardItems.RemoveAt(indexOfDraggedElement);
                    ScrumBoardItems.Insert(index, e.Cursor.Data as UserStory);
                }
            }
            else
            {
                //test--------------------------------------------
                //Task item = e.Cursor.Data as Task;
                //if (item.DraggedElement is ObservableCollection<Task>)
                //{
                //    ObservableCollection<Task> orig = item.DraggedElement as ObservableCollection<Task>;
                //    orig.Insert(0,item);
                //}                
            }
        }

        private void sp_DragCompleted(object sender, SurfaceDragCompletedEventArgs e)
        {
            if (((SurfaceListBox)sender).Name == "sp" && e.Cursor.Data is UserStory)
            {
                //Console.WriteLine("complete");
            }
            else
            {
                //Console.WriteLine(e.Source);
                //Console.WriteLine(e.OriginalSource);                
            }
           
        }

        private void sp_DragCanceled(object sender, SurfaceDragDropEventArgs e)
        {
            if (((SurfaceListBox)sender).Name == "sp" && e.Cursor.Data is UserStory)
            {
                //Console.WriteLine("cancel");
            }
            else
            {
                //Console.WriteLine(e.Source);
                //Console.WriteLine(e.OriginalSource);                
            }
        }

        #region help function for listbox insertion

        // controls to help swap and insert task cards inside the listbox
        public delegate Point GetDragDropPosition(IInputElement theElement);

        private bool isTheCursorOnTarget(Visual target, GetDragDropPosition pos)
        {
            Rect posBounds = VisualTreeHelper.GetDescendantBounds(target);
            Point theCursorPos = pos((IInputElement)target);
            return posBounds.Contains(theCursorPos);
        }

        private ListBoxItem GetListBoxItem(ListBox listBox, int index)
        {
            if (listBox.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                return null;
            return listBox.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem;
        }

        private int GetListBoxItemCurrentIndex(ListBox listBox, GetDragDropPosition pos)
        {
            int curIndex = -1;
            for (int i = 0; i < listBox.Items.Count; i++)
            {
                ListBoxItem item = GetListBoxItem(listBox, i);
                if (isTheCursorOnTarget(item, pos))
                {
                    curIndex = i;
                    break;
                }
            }
            return curIndex;
        }

        #endregion        

       
    }
}
